﻿namespace USElections.TileUpdates
{
    using System;
    using System.Linq;
    using Microsoft.Phone.Shell;
    using USElections.Model;

    /// <summary>
    /// ApplicationTile class.
    /// </summary>
    public static class ApplicationTile
    {
        /// <summary>
        /// Set photo of Voted candidate.
        /// </summary>
        public static void SetPhoto()
        {
            ShellTile tileToFind = ShellTile.ActiveTiles.First();

            Uri backBackgroundImage = null;
            string backTitle = string.Empty;
            string backContent = string.Empty;

            if (tileToFind != null)
            {
                /* check if user voted, if so, set as background image */
                int votedcandidate = NorthernLights.PersistentVariables.Get<int>(Model.Enums.Variables.VotedCandidate.ToString());

                if (votedcandidate != default(int))
                {
                    Candidate candidate = Data.Instance.Candidates.GetCandidateById(votedcandidate);

                    if (candidate != null)
                    {
                        if (!string.IsNullOrEmpty(candidate.ImageUri))
                        {
                            backBackgroundImage = new Uri(candidate.ImageUri, UriKind.Relative);
                            backContent = candidate.FullName;
                            backTitle = "US Elections";
                        }
                    }
                }

                StandardTileData newTileData = new StandardTileData
                {
                    BackBackgroundImage = backBackgroundImage,
                    BackContent = backContent,
                    BackTitle = backTitle,
                };

                tileToFind.Update(newTileData);
            }
        }

        /// <summary>
        /// Update application Tile.
        /// </summary>
        /// <param name="count">The value for the counter</param>
        public static void Update(int count)
        {
            ShellTile tileToFind = ShellTile.ActiveTiles.First();

            if (tileToFind != null)
            {
                StandardTileData newTileData = new StandardTileData
                {
                    Count = count,
                };

                tileToFind.Update(newTileData);
            }
        }
    }
}
